Plotly (link here) is one of the two ways we will discuss to make interactive graphs. You can embed them in the application “Dash” to make dashboards, but also you can also just make your reports dynamic.

also, you’ll notice that this github is setup with a special new ability - This is a website now too, displaying the html of the report!

Penguin Plot

First, we make the plot, by saving the ggplot as an object.

library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   4.0.0     ✔ tibble    3.3.0
## ✔ lubridate 1.9.4     ✔ tidyr     1.3.1
## ✔ purrr     1.1.0     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(palmerpenguins)
## 
## Attaching package: 'palmerpenguins'
## 
## The following objects are masked from 'package:datasets':
## 
##     penguins, penguins_raw
p <- ggplot(penguins, aes(x = bill_length_mm, y = bill_depth_mm, col = species)) + geom_point()
p
## Warning: Removed 2 rows containing missing values or values outside the scale range
## (`geom_point()`).

Penguin Plotly

Then, all we need to do is to use the function ggplotly()!

library(plotly)
## Warning: package 'plotly' was built under R version 4.5.2
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
ggplotly(p)
p_animated <- ggplot(penguins, aes(
  x = bill_length_mm,
  y = bill_depth_mm,
  color = species,
  frame = island)) +
  geom_point(size = 2, alpha = 0.7) +
  labs(
    title = "Animated Penguin Plot by Island",
    x = "Bill Length (mm)",
    y = "Bill Depth (mm)"
  )

ggplotly(p_animated)
## Warning in p$x$data[firstFrame] <- p$x$frames[[1]]$data: number of items to
## replace is not a multiple of replacement length